const sampler_t sampler = CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST;

__kernel void Median(__read_only image2d_t src, __write_only image2d_t dest){
    
    //quick and dirty with out the use of vectotization and it branchs every were
    
    int x = get_global_id(0), y = get_global_id(1);
    
    if (x >= get_image_width(src) || y >= get_image_height(src))
    return;
    
    int2 cord = (int2)(x,y);
    
    float4 pix = read_imagef(src,sampler,cord);
    float4 p00 = read_imagef(src, sampler, (int2)(x - 1, y - 1));
    float4 p10 = read_imagef(src, sampler, (int2)(x, y - 1));
    float4 p20 = read_imagef(src, sampler, (int2)(x + 1, y - 1));
    float4 p01 = read_imagef(src, sampler, (int2)(x - 1, y));
    float4 p21 = read_imagef(src, sampler, (int2)(x + 1, y));
    float4 p02 = read_imagef(src, sampler, (int2)(x - 1, y + 1));
    float4 p12 = read_imagef(src, sampler, (int2)(x, y + 1));
    float4 p22 = read_imagef(src, sampler, (int2)(x + 1, y + 1));
    
    //place the sub colors into their respective arrays
    float redPix[] = {p00.x,p01.x,p02.x,p10.x,pix.x,p12.x,p20.x,p21.x,p22.x};
    float greenPix[] = {p00.y,p01.y,p02.y,p10.y,pix.y,p12.y,p20.y,p21.y,p22.y};
    float BluePix[] = {p00.z,p01.z,p02.z,p10.z,pix.z,p12.z,p20.z,p21.z,p22.z};
    
    
    
    //bubble sort on every element
    int i,j;
    float temp;
    int s = 9;
          //sort red color
    for(i=0;i<s;i++)for(j=i+1;j<s;j++)if(redPix[i]>redPix[j]){
               temp=redPix[i];
              redPix[i]=redPix[j];
              redPix[j]=temp;
           }
           //sort green color
    for(i=0;i<s;i++)for(j=i+1;j<s;j++)if(greenPix[i]>greenPix[j]){
              temp=greenPix[i];
              greenPix[i]=greenPix[j];
              greenPix[j]=temp;
           }
           //sort blue color
    for(i=0;i<s;i++)for(j=i+1;j<s;j++)if(BluePix[i]>BluePix[j]){
              temp=BluePix[i];
              BluePix[i]=BluePix[j];
              BluePix[j]=temp;
           }
    write_imagef(dest,cord,(float4)(redPix[4],greenPix[4],BluePix[4],1.0f));
}